package com.vader.springcloud.controller;

import com.vader.springcloud.entities.CommonResult;
import com.vader.springcloud.entities.mapper.PaymentDO;
import com.vader.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author kaivader
 */
@RestController
@RequestMapping("/payment")
@Slf4j
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @Resource
    private DiscoveryClient discoveryClient;

    @RequestMapping("insert")
    CommonResult<Object> insert(@RequestBody PaymentDO paymentDO) {
        int result = paymentService.insert(paymentDO);
        log.info("插入{}订单",result);
        if (result>0){
            return new CommonResult(200,"插入成功"+serverPort,result);
        }else {
            return new CommonResult(444,"插入失败",null);
        }
    }

    @GetMapping("/query/{id}")
    CommonResult<Object> query(@PathVariable("id") Long id){
        return new CommonResult(200,"查询结果"+serverPort,paymentService.queryById(id));
    }

    @GetMapping("/discovery")
    Object discovery(){
        List<String> services = discoveryClient.getServices();
        for (String s:services){
            log.info("*******服务"+s);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance info:instances){
            log.info(info.getHost()+"\t"+info.getPort()+"\t"+info.getInstanceId()+"\t"+info.getUri());
        }
        return discoveryClient;
    }

    @GetMapping("/lb")
    String lb(){
        return serverPort;
    }
}
